package com.lagou.conf;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selects = rootElement.selectNodes("select"); // 查询
        List<Element> updates = rootElement.selectNodes("update"); // 增删改
        selects.addAll(updates);
        for (Element element : selects) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            boolean isUpdate = "update".equals(element.getName()); // 是否为增删改

            // statementId
            String key = namespace + "." + id;
            // sql语句
            String textTrim = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType == null ? Void.class : Class.forName(parameterType));
            mappedStatement.setResultType(resultType == null ? Void.class : Class.forName(resultType));
            mappedStatement.setSql(textTrim);
            mappedStatement.setUpdate(isUpdate);
            System.out.println(String.format(
                    "[register mapper] statementId=%s, sql=%s, paramType=%s, resultType=%s, isUpdate=%s",
                    key, textTrim, parameterType, resultType, isUpdate));
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
